package cn.xz.mxxz.util

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.widget.Toast

/**
 * 跳转到其他APP
 * */
object JumpAppUtil {

    //url-包名
    fun to(context: Context, url: String){
        if (getApp(context,url)){
            val intent = context.packageManager.getLaunchIntentForPackage(url)
            if (intent != null) {
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                context.startActivity(intent)
            }
        }else{
            Toast.makeText(context,"目标应用未安装",Toast.LENGTH_SHORT).show()
        }
    }

    //url-包名
    //activity - 要跳转的界面名称
    //在manifest文件添加  android:exported="true"
    fun to(context: Context, url: String,activity: String){
        if (getApp(context,url)){
            val intent = Intent(Intent.ACTION_MAIN)
            val componentName = ComponentName(url, activity)
            intent.component = componentName
            context.startActivity(intent)
        }else{
            Toast.makeText(context,"目标应用未安装",Toast.LENGTH_SHORT).show()
        }
    }

    //判断当前应用是否存在
    private fun getApp(context: Context, url: String): Boolean{
        var packageInfo: PackageInfo? = null
        try {
            packageInfo = context.packageManager.getPackageInfo(url, 0)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return packageInfo != null
    }
}